package top.huhuiyu.springboot3.service.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot3.base.R;
import top.huhuiyu.springboot3.dao.api.TbDataHistoryMapper;
import top.huhuiyu.springboot3.entity.api.HistoryResult;
import top.huhuiyu.springboot3.entity.api.TbDataHistory;
import top.huhuiyu.springboot3.service.BaseApiService;
import top.huhuiyu.springboot3.service.api.HistoryService;
import top.huhuiyu.springboot3.util.JsonUtils;

@Service
@RequiredArgsConstructor
@Slf4j
public class HistoryServiceImpl extends BaseApiService implements HistoryService {
    private final RestTemplate restTemplate;
    private final TbDataHistoryMapper tbDataHistoryMapper;

    @Override
    public HistoryResult getHistory() {
        String url = String.format(HISTORY_URL, "1");
        String result = restTemplate.exchange(url, HttpMethod.GET, buildHttpEntity(), String.class).getBody();
        log.debug("获取历史上的今天的原始数据：{}", result);
        if (StringUtils.hasText(result)) {
            return JsonUtils.parse(result, HistoryResult.class);
        }
        return null;
    }

    @Override
    public int makeHistoryData() {
        HistoryResult history = getHistory();
        if (history == null) {
            return 0;
        }
        int count = 0;
        for (HistoryResult.HistoryData data : history.getData()) {
            TbDataHistory tbDataHistory = TbDataHistory.from(data);
            // 如果数据不存在才会添加
            QueryWrapper<TbDataHistory> wrapper = new QueryWrapper<>();
            wrapper.eq("title", tbDataHistory.getTitle());
            if (tbDataHistoryMapper.selectOne(wrapper) == null) {
                tbDataHistoryMapper.insert(tbDataHistory);
                count++;
            }
        }
        return count;
    }

    @Override
    public R<TbDataHistory> randHistory() {
        TbDataHistory history = tbDataHistoryMapper.randHistory();
        if (history == null) {
            return R.fail("没有数据", null);
        }
        return R.ok(history);
    }
}
